<template>
  <view class="main-container">
    <view class="hotel-title">
      <wd-icon name="thin-arrow-left" size="18px" @click="pageBack"></wd-icon>
      <view class="hotel-name">订单信息</view>
      <view style="width: 50rpx;"></view>
    </view>
    <!-- 订单信息 -->
    <view class="order-info">
      <image style="width: 25%;height: 180rpx;border-radius: 10rpx;" :src="orderData.headImgUrl"></image>
      <view class="order-details">
        <view class="date">{{ hotelStore.beginDate }} 周{{ hotelStore.firstweek }} - {{ hotelStore.endDate }} 周{{ hotelStore.lastweek }} | {{ hotelStore.dayCount }}晚</view>
        <view class="room" v-if="!order.isBreakfast">{{ order.name }} | {{ order.area }} m² | 无早餐</view>
        <view class="room" v-else>{{ order.name }} | {{ order.area }} m² | {{ order.isBreakfast}}份早餐</view>
		<view class="room-bedType room-detail"><span v-for="(tag,index) in order.bedType.split(',')" :key="index">{{tag.split("-")[0]}}张{{ getbad(tag) }} &nbsp;·&nbsp; </span> {{ order.liveNumber }} 人入住</view>
        <!-- <view class="room">{{order.bedType.split("-")[0]}}张{{ getbad(order.bedType) }}</view> -->
        <!-- <view class="cancel-policy">{{ order.checkInTime }}入住 - {{ order.checkOutTime }}退房</view> -->
        <view class="cancel-policy">{{ order.checkOutPolicy }}</view>
      </view>
    </view>
    <!-- 订单填写 -->
    <view class="section">
      <view class="info-item">
        <view class="section-title"><image class="contentIcon" src="http://img.jowong.com/aba/2025-04-24/yudingtubiao_1745486450173.png" mode=""></image> 订房信息</view>
        <wd-input-number v-model="orderData.houseNumber" @change="handleChange" />
      </view>
      <view class="info-item">
        <view class="tourname">
          <text>房客姓名</text>
          <text class="input-value">{{ orderData.customerName }}</text>
        </view>
        <wd-icon name="usergroup-add" color="#1B9C61" size="22px" @click="addTourList"></wd-icon>
      </view>
      <view class="info-item">
        <text>联系电话</text>
        <input v-model="orderData.contactNumber" placeholder="请输入手机号" class="input-box"/>
      </view>
    </view>

    <!-- 备注信息 -->
    <view class="section">
      <view class="section-title"><image class="contentIcon" src="http://img.jowong.com/aba/2025-04-24/beizhu_1745486418821.png" mode=""></image>️ 备注信息</view>
      <textarea v-model="orderData.memo" placeholder="请输入备注" class="textarea"></textarea>
    </view>

    <!-- 预定须知 -->
    <view class="section text">
      <view class="section-title"><image class="contentIcon" src="http://img.jowong.com/aba/2025-04-24/xuzhi_1745486387127.png" mode=""></image> 预定须知</view>
      <text class="notice">{{ order.reserveExplain }}</text>
    </view>
    <!-- 预定按钮 -->
    <view class="btn-bottom-container">
      <view class="top-container flex ">
        <view class="price">￥  {{orderData.payAmount}}</view>
        <view class="right-container">
          <view class="price-detail-tip" @click="showdetails">
            <text>明细</text>
            <wd-icon name="arrow-down" size="22px"></wd-icon>
          </view>
          <view class="btn" @click="gotoOrder">去支付</view>
        </view>
      </view>
      <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
    </view>
    <wd-action-sheet v-model="isShowDetails" @close="closedetails">
      <view style="padding: 15px 15px 150px 15px;">
        <view class="hoteltile">{{order.hotelname}}</view>
        <view class="dateprice ">
          <view class="">房间数量</view> 
          <view class="">{{order.name}} * {{orderData.houseNumber}}</view>
        </view>
		<view style="border: 1rpx solid #d8d8d8;border-radius: 10rpx;">
			<view class="dateprice">
			  <view class="">日期</view>
			  <view class="">价格</view>
			</view>
			<view class="dateprice" v-for="item in negotiatedPrice" :key="item">
			  <view class="">{{item.houseDate}}</view>
			  <view class="">￥ {{item.negotiatedPrice}}</view>
			</view> 
		</view>
        
        <view class="dateprice ">
          <view class="">总金额</view>
          <view class="">￥ {{orderData.totalAmount}}</view> 
        </view>
        <view class="dateprice ">
          <view class="">优惠金额</view>
          <view class="">￥ {{orderData.discountAmount}}</view>
        </view>
        <view class="dateprice ">
          <view class="">实际金额</view>
          <view class="">￥ {{orderData.payAmount}}</view>
        </view>
      </view>
      <view class="btn-bottom-container">
        <view class="top-container flex ">
          <view class="price">￥  {{orderData.payAmount}}</view>
          <view class="right-container">
            <view class="price-detail-tip" @click="showdetails">
              <text>明细</text>
              <wd-icon name="arrow-down" size="22px"></wd-icon>
            </view>
            <view class="btn" @click="gotoOrder">去支付</view>
          </view>
        </view>
        <view class="safe-content" :style="{height: safeInsert + 'px'}"></view>
      </view>
    </wd-action-sheet>
  </view>

	<AddTourist
	  :showAddTourist="showAddTourist"
	  :touristInfoList="touristInfoList"  
	  @close="closeAddTourist"
	  @queryTouristList="queryTouristList(false)"
	></AddTourist>

</template>
 
<script setup >
import {ref,reactive} from "vue";
import {onLoad} from "@dcloudio/uni-app";
import {commonWordList} from "@/api/system";
import {touristList} from "@/api/common";
import AddTourist from "@/components/AddTourist/index.vue";
import {commitOrder,toPay,roomDetail} from "@/hotelHomestay/api/hotelHomestay";
import useHotelStore from '@/store/hotel';
// import wxPay from "@/utils/pay"; 

const hotelStore = useHotelStore();

const safeInsert = ref(0);
const isShowDetails = ref(false)
const pageBack = () =>{
  uni.navigateBack()
}
const value = ref(1)
const showAddTourist = ref(false);
const order = ref({});

const touristInfoList = ref([]);
const orderData = reactive({ 
  productId: '', //房型id 
  houseName: "",//房型名称
  customerName: "", //联系人
  contactNumber: "", //联系电话
  idCard: "", //身份证
  checkInTime: hotelStore.beginDate , //入住时间
  checkOutTime: hotelStore.endDate , //离店时间
  houseNumber: 1, //房间数量
  merchantId: 1, //商户id
  merchantName:'',
  payAmount: 0,//支付金额
  totalAmount: 0,//实际金额 
  discountAmount: 0,//优惠金额 
  status: 0,
  channel: 0,
  source: 0,
  headImgUrl:'',//房间图片
  productDescribed:'',//早餐,大床,面积
  memo:''
})
const getUserData = (data) => { 
  orderData.customerName = data.name
  orderData.contactNumber = data.Phone
  showAddTourist.value = false;
};
const showdetails = () => { 
  isShowDetails.value = !isShowDetails.value;
};
const closedetails = () => {
  isShowDetails.value = false;
};
function handleChange({ value }) { 
  orderData.totalAmount = order.value.livePrice.reduce((sum, item) => sum + item.negotiatedPrice, 0) * value
  orderData.payAmount = orderData.totalAmount - orderData.discountAmount
}

const addTourList = () => {
  showAddTourist.value = true;  // Show the addTourist component
};

const closeAddTourist = (e) => {
  orderData.customerName = touristInfoList.value.filter(item => e.choiceTouristIdList.includes(item.id)).map(item => item.name).join('，');
  orderData.contactNumber = touristInfoList.value.filter(item => e.choiceTouristIdList.includes(item.id)).map(item => item.tel).join('，');
  orderData.idCard = touristInfoList.value.filter(item => e.choiceTouristIdList.includes(item.id)).map(item => item.idCard).join('，');
  showAddTourist.value = false;  // Hide the addTourist component 
};
const gotoOrder = () =>{ 
  commitOrder(orderData).then(res=>{  
	 handleToPay(res.result.orderId);
  })

}

const handleToPay = async (id) => {
	// #ifdef MP-WEXIN
	// #endif
	await toPay({type:"jsapi",id}).then(res => {
	  let { appId,nonceStr, packageValue,paySign,signType,timeStamp } = res.result;
	  uni.navigateTo({
		url:`/ticketSubPack/pages/PaymentOrder/index?totalPrice=${orderData.payAmount}&timeStamp=${timeStamp}&nonceStr=${nonceStr}&packageValue=${encodeURIComponent(packageValue)}&signType=${signType}&paySign=${encodeURIComponent(paySign)}&orderId=${id}`
	  })
	 /* wxPay(timeStamp,nonceStr,packageValue,signType,paySign);*/
	});
}; 
  const queryTouristList = async (isShowLoad) => {
    await touristList({pageSize:99,userId:2}).then(res => { 
      touristInfoList.value = res.result;
    });
  };
  onShow(async() => {
    await queryTouristList(true);
  });
const negotiatedPrice = ref([])


const badData = ref([]) 
const queryCommonWordList = async () => {
	await commonWordList({keys:"HOTEL_HOUSE_BED_TYPE"}).then(res => { 
		badData.value = res.result.HOTEL_HOUSE_BED_TYPE
		orderData.productDescribed = getbad(order.value.bedType)+' | '+order.value.isBreakfast+'份早餐 | '+order.value.area+'m²'
	}); 
}; 
const getbad = (val)=>{
	const num = val.split("-")[1];
	return badData.value.find(item => item.code == num)?.name || '';
}  
const getRoomDatil = (id) => {
  roomDetail(id).then(res=>{ 
	// console.log(res);
	orderData.headImgUrl = res.result.headImageUrl
  })
} 
onLoad((options)=>{
  safeInsert.value = uni.getSystemInfoSync().safeAreaInsets.bottom
  if (options.roomData) {
    const roomData = JSON.parse(decodeURIComponent(options.roomData)); 
    orderData.productId = roomData.id 
    orderData.houseName = roomData.name
    orderData.merchantId = roomData.merchantId
    orderData.merchantName = roomData.hotelname
    negotiatedPrice.value = roomData.livePrice
    orderData.totalAmount = roomData.livePrice.reduce((sum, item) => sum + item.negotiatedPrice, 0);
    orderData.payAmount = orderData.totalAmount - orderData.discountAmount 
    order.value = roomData
	getRoomDatil(roomData.id) 
	queryCommonWordList()
  }
})
</script>


<style lang="scss" scoped>
.contentIcon{
	width: 35rpx;
	height: 35rpx;
	position: relative;
	top: 8rpx;
	// margin: 20rpx 0 0 0;
}
.dateprice{
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
}
.hoteltile{
  font-size: 36rpx;
  font-weight: 600;
  padding: 20rpx;

}
.main-container{
  padding: 0 20rpx;
  min-height: 100vh;
  background: linear-gradient(to bottom, #A7C6AC 0%, #EEEFE7 15%);

  .hotel-title{
    height: 62rpx;
    display: flex;
    padding:13.5% 0 30rpx 0;
    align-items: center;
  }
  .hotel-name{
    width:100%;
    height: 100%;
    font-family: PingFang SC;
    font-weight: 500;
    font-size: 33rpx;
    color: #2B2B24;
    text-align: center;
    line-height: 60rpx;
  }
  .hotel-phone{
    width: 35rpx;
    height: 35rpx;
    margin-top: 10rpx;
  }
  /* 订单信息 */
  .order-info {
    display: flex;
    // background: #fff;
    // padding: 15px;
    border-radius: 8rpx;
    // margin: 10px;
  }

  .hotel-img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 10rpx;
    margin-right: 20rpx;
  }

  .order-details {
    flex: 1;
	padding: 0 20rpx;
  }

  .date {
    font-size: 26rpx;
    font-weight: bold;
  }

  .room {
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 25rpx;
    color: #333333;
    margin: 15rpx 0;
  }
  
  .room-bedType{
  	display: flex;
  	flex-wrap: wrap;
  	font-family: PingFang SC;
  	font-weight: 500;
  	font-size: 22rpx;
  	color: #2B2B24;
  	margin: 5rpx 0 0 0 ; 
  }
  .room-detail{
  	width: 100%;
  	margin: 10rpx 0;
  	font-family: PingFang SC;
  	font-weight: 500;
  	font-size: 22rpx;
  	color: #2B2B24;
  }
  .cancel-policy {
    font-size: 24rpx;
    color: #ff7d00;
    margin: 15rpx 0;
  }

  /* 订单填写 */
  .section {
    background: #fff;
    padding: 20rpx 30rpx;
    border-radius: 16rpx;
    margin: 10px 0;
  }
  .text{ 
    min-height: 200rpx; }
  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    margin-bottom: 20rpx;
    display: block;
  }

  .info-item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;
    font-size: 28rpx;
    border-bottom: 1px solid #eee;
  }

  .input-value {
    font-family: PingFang SC;
    font-weight: 800;
    font-size: 33rpx;
    color: #333333;
    margin-left: 20rpx;
  }

  .input-box {
    flex: 1;
    border: none;
    text-align: right;
    font-size: 28rpx;
    color: #666;
  }
  .tourname{
    width: 90%;
    font-family: PingFang SC;
    font-weight: 400;
    font-size: 33rpx;
    color: #333333;
  }
  .textarea {
    width: 90%; 
    height: 140rpx; 
    border: none;
    font-size: 28rpx;
    color: #666;
    background: #f8f8f8;
    padding: 5%;
    border-radius: 10rpx;
  }

  /* 预定须知 */
  .notice {
    font-size: 26rpx;
    color: #666;
    line-height: 1.5;
  }
  /* 底部提交 */
  .bottom-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #feffec;
    padding: 20rpx 5% 40rpx 5%;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
  }

  .total-price {
    width: 65%;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 42rpx;
    color: #AA5413;
  }

  .book-btn {
    width: 164rpx;
    height: 83rpx;
    background: #1B9C61;
    border-radius: 10rpx;
    font-family: PingFang SC;
    font-weight: bold;
    font-size: 33rpx;
    color: #FDFFEB;
  }

}
.btn-bottom-container {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  background: #fdffeb;
  .top-container {
    justify-content: space-between;
    align-items: center;
    padding: 32rpx 20rpx 0 59rpx;
    .price {
      font-size: 42rpx;
      font-weight: bold;
      color: #AA5413;
    }
    .right-container {
      display: flex;
      align-items: center;
      .price-detail-tip {
        display: flex;
        align-items: center;
        padding-right: 11rpx;
        text {
          font-size: 30rpx;
        }
      }
      .btn {
        border-radius: 10.5rpx;
        font-weight: bold;
        padding: 25rpx 32rpx;
        color: #FDFFEB;
        background: #AA5413;
      }
    }
  }
}
</style>
